﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OOAD_Project_Editor.Foundation;

namespace OOAD_Project_Editor.Application
{
    class FileHanlder : IFileHanlder
    {
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        public FileHanlder(string fileType)
        {
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = fileType + " files (*." + fileType + ")|*." + fileType;
            openFileDialog1.RestoreDirectory = true;

            saveFileDialog1.Filter = fileType + " files (*." + fileType + ")|*." + fileType;
            saveFileDialog1.RestoreDirectory = true;
        }

        public bool SaveFile(object file)
        {
            Stream myStream = null;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = saveFileDialog1.OpenFile()) != null)
                    {
                        StreamWriter writer = new StreamWriter(myStream);
                        writer.Write(file);
                        writer.Close();
                        myStream.Close();
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
            return false;
        }

        public string OpenFile()
        {
            string filePath = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Stream stream = null;
                try
                {
                    stream = openFileDialog1.OpenFile();
                    if (stream != null)
                    {
                        filePath = openFileDialog1.FileName;
                    }
                    stream.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }


                if (filePath != null && filePath.Length > 0)
                    return filePath;
                else
                    throw new FileNotFoundException();
            }
            return null;
        }

    }
}
